package com.atguigu.flume.interceptor;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

/**
 * logFile-->kafka
 * 过滤掉不是json格式的数据
 */
public class LogInterceptor implements Interceptor {

    JsonParser parser;

    public void initialize() {
        parser=new JsonParser();
    }

    /**
     * 确保嗯event不是json格式就返回null
     * @param event
     * @return
     */
    public Event intercept(Event event) {
        byte[] body = event.getBody();
        JsonElement parse;
        try {
            parse = parser.parse(new String(body, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return event;
    }

    public List<Event> intercept(List<Event> events) {
        //过滤掉不是json格式的数据
        Iterator<Event> iterator = events.iterator();
        while (iterator.hasNext()){
            if (intercept(iterator.next())==null){
                iterator.remove();
            }
        }
        return events;
    }

    public void close() {

    }

    public static class Builder implements Interceptor.Builder {
        public Interceptor build() {
            return new LogInterceptor();
        }
        /**
         * 配置方法，可以从配置文件中配置我们的Interceptor
         * @param context 配置文件
         */
        public void configure(Context context) {

        }
    }
}
